package com.deep.deepenterprise.api.interceptor;

import com.deep.deepenterpise.common.DrAESCommon;
import com.deep.deepenterpise.common.code.DrCodeMsg;
import com.deep.deepenterprise.api.threadlocal.DrLoginTokenContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author xyz
 * @description Dr拦截器，用于token认证和黑名单
 * @time 2024/4/16 11:30
 */
@Component
@Slf4j
public class DrAccessInterceptor extends DrBaseAccessInterceptor implements AsyncHandlerInterceptor {

    /**
     * 方法执行前
     *
     * @param request  请求
     * @param response 响应
     * @param handler  数据
     * @return boolean
     * @throws Exception error
     */
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler)
            throws Exception {
        // 验证token
        String drToken = request.getHeader("Drtoken");
        if (StringUtils.isBlank(drToken)) {
            // token不存在
            render(response, DrCodeMsg.TOKEN_ERR);
            return false;
        }

        // 验证token
        /*if (!DrAuthUtil.checkAuth(drToken)) {
            render(response, DrCodeMsg.AUTH_ERR);
            return false;
        }*/

        String drUserUuid = DrAESCommon.parseToken(drToken);
        if (StringUtils.isBlank(drUserUuid)) {
            // token解析失败
            render(response, DrCodeMsg.TOKEN_ERR);
            return false;
        }

        // 保存用户uuid
        DrLoginTokenContext.setUserId(drUserUuid);

        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
                           @NotNull Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
                                @NotNull Object handler, Exception ex) throws Exception {
        if (DrLoginTokenContext.exists()) {
            DrLoginTokenContext.remove();
        }
    }
}
